package com.example.demo.mapper;

import com.example.demo.model.InviteCode;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface InviteCodeMapper {
    @Insert("INSERT INTO invite_code (code, creator_id, created_at, is_used, expires_at) " +
            "VALUES (#{code}, #{creatorId}, #{createdAt}, #{used}, #{expiresAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(InviteCode inviteCode);

    @Select("SELECT * FROM invite_code WHERE code = #{code}")
    InviteCode findByCode(String code);

    @Update("UPDATE invite_code SET is_used = #{used}, used_by = #{usedBy}, used_at = #{usedAt} WHERE id = #{id}")
    void update(InviteCode inviteCode);

    @Select("SELECT * FROM invite_code WHERE creator_id = #{creatorId} AND is_used = false AND expires_at > NOW()")
    List<InviteCode> findValidCodesByCreator(Long creatorId);

    @Select("SELECT COUNT(*) FROM invite_code WHERE creator_id = #{creatorId}")
    int countByCreator(Long creatorId);

    @Select("SELECT * FROM invite_code WHERE creator_id = #{creatorId} ORDER BY created_at DESC")
    List<InviteCode> findAllCodesByCreator(Long creatorId);

    @Select("SELECT * FROM invite_code WHERE creator_id = #{creatorId} AND is_used = true ORDER BY used_at DESC")
    List<InviteCode> findUsedCodesByCreator(Long creatorId);

    @Delete("DELETE FROM invite_code WHERE expires_at < #{currentTime}")
    void deleteExpiredCodes(LocalDateTime currentTime);

    @Delete("DELETE FROM invite_code WHERE is_used = true AND used_at < #{threshold}")
    void deleteUsedCodesOlderThan(LocalDateTime threshold);
}